(function() {
	mui.plusReady(function() {
		var types = {};
		types[plus.networkinfo.CONNECTION_UNKNOW] = "Unknown connection";
		types[plus.networkinfo.CONNECTION_NONE] = "None connection";
		types[plus.networkinfo.CONNECTION_ETHERNET] = "Ethernet connection";
		types[plus.networkinfo.CONNECTION_WIFI] = "WiFi connection";
		types[plus.networkinfo.CONNECTION_CELL2G] = "Cellular 2G connection";
		types[plus.networkinfo.CONNECTION_CELL3G] = "Cellular 3G connection";
		types[plus.networkinfo.CONNECTION_CELL4G] = "Cellular 4G connection";

		var token = localStorageFunc.get('token');
		var userid = localStorageFunc.get('token').userId;
		var uri = 'ws://' + config.getServer + '?clientid=1&userid=' + userid + '&token=' + token.refresh_token;
		console.log('uri:' + uri);
		var ws;
		var hearbeatTimer; // 心跳轮询
		var lastTimeHeartbeat = null; // 最近心跳时间
		var heatbeatInterval = 10000; // 心跳间隔（毫秒）
		var reConnectCount = 0; // 重连次数
		var reCounectMax = 10; // 最大重连次数

		// 生成uuid
		function uuid() {
			var s = [];
			var hexDigits = "0123456789abcdef";
			for(var i = 0; i < 36; i++) {
				s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
			}
			s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
			s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
			s[8] = s[13] = s[18] = s[23] = "-";

			var uuid = s.join("");
			return uuid;
		}

		// 发送聊天消息
		var send = function(msg) {
			msg.data.id = uuid();
			msg.data.sender = userid;
			console.log('send msg:' + JSON.stringify(msg));
			var str = JSON.stringify(msg);
			if(ws && ws.readyState == 1) {
				ws.send(str);
				var chatPage = plus.webview.getWebviewById('im-chat'); // 找到打开的聊天页
				if(chatPage) { // 消息推送至聊天页
					mui.fire(chatPage, 'monitorImT', msg);
				}
			} else {
				mui.toast('IM连接异常，请重试');
			}
		}

		// 处理服务器响应的消息
		var handleRspMsg = function(data) {
			switch(data.type) {
				case 'auth': // 鉴权结果
					console.log('im auth rsp:' + JSON.stringify(data));
					if(data.code != 0) {
						mui.toast('IM服务认证失败，请重新登陆');
					}
					break;
				/*case 'singleChat': // 单聊发送结果
				case 'groupChat': // 群聊发送结果
					console.log('data：' + data);
					var chatPage = plus.webview.getWebviewById('im-chat');
					if(chatPage) {
						mui.fire(chatPage, 'msgRsp', data);
					}
					break;*/
				default:
					break;
			}
		}

		// 处理收到的聊天消息
		var handleChatMsg = function(msg) {
			console.log('msg:' + JSON.stringify(msg));
			var chatPage = plus.webview.getWebviewById('im-chat'); // 找到打开的聊天页
			if(chatPage) { // 消息推送至聊天页
				mui.fire(chatPage, 'newMsg', msg);
			} else { //如果聊天页未打开的时候就推送到最近回话页
				var msgPage = plus.webview.getWebviewById('/html/sub-message.html'); // 新消息推送至最近会话页
				if(msgPage) {
					msg.read = 0;
					mui.fire(msgPage, 'newChatMsg', msg);
				}
			}
			
			
			//	收到服务器错误回执时
			if(msg.data.code) {
				var chatPage = plus.webview.getWebviewById('im-chat'); // 推送到消息页面
				if(chatPage) { // 消息推送至聊天页
					mui.fire(chatPage, 'msgError', msg);
				}
			}

		}

		var connect = function() {
			ws = new WebSocket(uri);
			ws.onopen = function() {
				// 发送心跳包&检测离线
				ws.send('hb');
				hearbeatTimer = setInterval(function() {
					if(lastTimeHeartbeat instanceof Date) {
						if(new Date().getTime() - lastTimeHeartbeat.getTime() > 2 * heatbeatInterval) {
							clearInterval(hearbeatTimer);
							lastTimeHeartbeat = null;
							ws.close();
							return;
						}
					}
					if(ws.readyState == 1) {
						ws.send('hb');
						console.log('send heartbeat');
					}
				}, heatbeatInterval);
				reConnectCount = 0;
				mui.toast('IM连接成功');
				console.log('im opened');
			};

			ws.onclose = function() {
				hearbeatTimer = null;
				clearInterval(hearbeatTimer);
				console.log('im closed');
				reConnect();
			};

			ws.onerror = function() {
				hearbeatTimer = null;
				clearInterval(hearbeatTimer);
				console.log('im error');
				mui.toast('IM连接错误，请重试');
			};

			ws.onmessage = function(e) {
				if(e.data == 'hb') { // 心跳包
					lastTimeHeartbeat = new Date();
					return;
				}
				var data = JSON.parse(e.data);
				if(data.type == 'rsp') { // 服务器响应的消息
					handleRspMsg(data.data);
				} else { // 处理收到的聊天消息
					handleChatMsg(data);
				}
			};
		};
		connect();

		var reConnect = function() {
			if(reConnectCount > reCounectMax - 1) {
				mui.alert('IM连接超时，请重试');
				return;
			}
			var delayTime = (reConnectCount + 1) * 2000;
			setTimeout(function() {
				console.log('reconnect ' + reConnectCount);
				reConnectCount++;
				if(ws && ws.readyState != 1) {
					connect();
				}
			}, delayTime);
		};

		// 消息发送事件，供聊天页面调用
		window.addEventListener('send', function(e) {
			send(e.detail);
		});

		// 监听切换到前台事件，若IM掉线则重连
		document.addEventListener("resume", function() {
			console.log('application resume');
			if(!ws || (ws && ws.readyState != 1)) {
				reConnectCount = 0;
				reConnect();
			}
		});

		//	监听手机网络,IM聊天时需要监听网络情况
		document.addEventListener('netchange', function(e) {
			var network = plus.networkinfo.getCurrentType();
			console.log('network:' + network + ' ' + types[network]);
			if(network > 1) { // 有网情况下重连
				connect();
			}
		});
	});
})();